<template>
	<!-- 差旅添加报销费用明细 -->
	<view>
		<view style="height: 100%;padding-top: 20rpx;padding-bottom: 120rpx;">
			<uni-forms ref="form" :modelValue="newEntity" label-width="110px">
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="票据日期:" :rules="$rules.handle.BillDate" required name="BillDate">
						<view @click="DateChange($event, 'BillDate')">
							<uni-easyinput v-model="newEntity.BillDate" :disabled="true" :inputBorder="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="关联行程客户:" name="CustomerName">

						<!-- 关联的沟通记录列表 -->
						<view v-if="newEntity.CustomerNameOptions && newEntity.CustomerNameOptions.length>0" style="">
							<block v-for="(item, index) in newEntity.CustomerNameOptions" :key="index">
								<view style="display: flex;flex-wrap: wrap;padding-left: 20rpx;padding-right: 20rpx;">
									<u-tag @close="tagCloseChange(index)"
										style="margin-right: 20rpx;margin-bottom: 15rpx;" :text="item.cCusName"
										type="primary" closeable />
								</view>

							</block>
						</view>
						<!--  -->
						<view v-else @click="CustomerChoice">
							<uni-easyinput v-model="newEntity.CustomerName" suffixIcon="compose" :inputBorder="false"
								:disabled="true" />
						</view>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="业务性质:" :rules="$rules.handle.ExpenseTypeName" required
						name="ExpenseTypeName">
						<!-- 暂时不删除 -->
						<!-- <uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
							v-model="entity.ExpenseType" :localdata="newExpenseTypeOptions"
							@change="selectOptionsChange($event, 'ExpenseType')" :disabled="disabled"></uni-data-select> -->
						<uni-data-picker popup-title="请选择业务性质" :localdata="ExpenseTypeTree"
							@change="pickerChange($event, 'ExpenseTypeName')" v-model="newEntity.ExpenseTypeName">
						</uni-data-picker>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="票据类型:" :rules="$rules.handle.BillType" required name="BillType">
						<uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
							v-model="newEntity.BillType" :localdata="newBillTypeOptions"
							@change="selectOptionsChange($event, 'BillType')" :disabled="disabled"></uni-data-select>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="发票分类:" :rules="$rules.handle.InvoiceClassification" required
						name="InvoiceClassification">
						<uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
							v-model="newEntity.InvoiceClassification" :localdata="newInvoiceClassificationOptions"
							@change="selectOptionsChange($event, 'InvoiceClassification')"
							:disabled="disabled"></uni-data-select>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="票面金额:" name="FaceAmount" :rules="$rules.handle.FaceAmount" required>
						<view>
							<uni-easyinput v-model="newEntity.FaceAmount" :inputBorder="false" type="number"
								@input="inputChange($event, 'FaceAmount')" :adjust-position="false" />
						</view>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="报销金额:" name="ReimburseAmount" :rules="$rules.handle.ReimburseAmount"
						required>
						<view>
							<uni-easyinput v-model="newEntity.ReimburseAmount" type="number"
								@input="inputChange($event, 'ReimburseAmount')" :adjust-position="false"
								:inputBorder="false" />
						</view>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="票据张数:" name="BillsNum">
						<view>
							<uni-easyinput v-model="newEntity.BillsNum" :inputBorder="false" />
						</view>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="是否无票支出:" name="IsNoTicket">
						<radio-group @change="switchChange">
							<view style="display: flex;">
								<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in IsNoTicketOptions"
									:key="item.value">
									<view class="flex Acenter" style="margin-right: 50rpx;margin-top: 10rpx;">
										<radio :value="item.value" :checked="item.value"
											style="transform: scale(0.8);" />
										<view>{{item.name}}</view>
									</view>

								</label>
							</view>
						</radio-group>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="摘要:" name="ItemAbstract">
						<uni-easyinput v-model="newEntity.ItemAbstract" type="textarea" :adjust-position="false"
							:inputBorder="false" />
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="附件:" name="reimburse_Files">
					</uni-forms-item>
				</view>
				<!-- 上传附件 -->
				<UploadCopy ref="UploadCopy" @handlerSuccess="handlerSuccess" @handlerRmoveFile="handlerRmoveFile">
				</UploadCopy>
			</uni-forms>
		</view>
		<view class="submitButton">
			<u-button type="primary" @click="handleSubmitDetailSave">保存</u-button>
		</view>

		<!-- 引用客户组件 -->
		<MyuserAssociation @customerChoice="Client" ref="MyuserAssociation" :isHidden="true" title="选择关联的客户" />

		<!-- 选择日期 -->
		<u-calendar v-model="isCalendar" :mode="mode" @change="calendarChange"></u-calendar>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	//客户
	import MyuserAssociation from "../../components/MyuserAssociation.vue";
	import UploadCopy from "../../components/uploadCopy.vue"
	// 引入公共头部组件
	import {
		Base_DistrictGetTreeDataList
	} from "@/api/interface.js";
	export default {
		components: {
			// 关联的客户组件
			MyuserAssociation,
			// 上传组件
			UploadCopy
		},
		data() {
			return {
				// 是否无票状态
				IsBill: 0, //默认否
				IsNoTicketOptions: [{
						value: '1',
						name: '是',
						checked: true
					},
					{
						value: '0',
						name: '否',
						checked: false
					}
				],
				// /上传文件列表
				reimburse_Files: [],
				disabled: false,
				// 是否展示弹窗
				show: false,
				// 是否显示日期弹窗
				isCalendar: false,
				// 日期选择
				mode: 'date',
				// 传递过来的行程主表明细对象
				entity: {},
				// 当前行程明细主表下的费用明细子表对象
				newEntity: {
					BillsNum: 1
				},
				// 点击的是出发日期还是到达日期
				DateType: "",
				// 城市地区树结构
				// 地区树结构
				dataTree: [],
				// 业务性质树结构数据
				ExpenseTypeTree: [],
				// 票据类型下拉列表数据
				newBillTypeOptions: [],
				// 费用类型下拉列表数据
				newExpenseTypeOptions: [],
				// 发票分类下拉列表数据
				newInvoiceClassificationOptions: [],
				// 所有公司下拉列表数据
				newCompayListOptions: [],
				selectCustomerList: [],
				options: {},

			}
		},
		computed: {
			...mapState(["BillTypeOptions", "ExpenseTypeOptions", "InvoiceClassificationOptions", "CompayListOptions",
				"Base_DistrictGetTreeDataOptions", "CustomerInfoOptions"
			]),
		},
		onShow() {
			// 业务性质树结构数据回显
			this.ExpenseTypeTree = this.ExpenseTypeOptions
			// 城市的确树结构
			this.dataTree = this.Base_DistrictGetTreeDataOptions
		},
		onLoad(options) {
			// 获取添加明细时存储的当前行程entity数据
			if (uni.getStorageSync('entity')) {
				let entity = JSON.parse(uni.getStorageSync('entity'))
				this.options = entity
				// 传递过来的行程主表对象
				this.entity = this.options
				// 默认赋值费用明细客户 从前面页面带过来  行程下的费用明细子表对象
				this.newEntity.CustomerName = this.options.CustomerName
				this.newEntity.CustomName = this.options.CustomerName
				this.newEntity.CustomId = this.options.CustomId
				this.newEntity.CustomerNameOptions = this.options.CustomerNameOptions

				this.$forceUpdate()
				console.log('获取缓存--', this.options, this.entity, this.newEntity)
			}
			// 移除entity缓存
			uni.removeStorageSync('entity')
			// 默认处理附件上传删除图标按钮
			this.disabled = false
			this.newBillTypeOptions = this.BillTypeOptions
			this.newExpenseTypeOptions = this.ExpenseTypeOptions
			this.newInvoiceClassificationOptions = this.InvoiceClassificationOptions
			this.newCompayListOptions = this.CompayListOptions
		},
		methods: {
			// 上传成功
			handlerSuccess(file, fileEntity, index) {
				var that = this
				console.log('差旅新增新增上传成功了----------------------获取过来的', file, fileEntity, index)
				if (file.reimburse_Files.length > 0) {
					let reimburse_Files = file.reimburse_Files
					this.reimburse_Files = reimburse_Files
					this.newEntity.reimburse_Files = reimburse_Files
					this.newEntity.Upload = file.Upload
				}
			},
			// 移除附件
			handlerRmoveFile(list, index) {
				console.log('移除附件', list, index)
				// // 视图删除
				// this.entity.reimburse_Files.splice(index, 1)
				// this.$refs.UploadCopy.handlerRemove(item, index)
				// this.$sucessToast('已删除')
			},
			// 已关联的客户列表标签列表删除
			tagCloseChange(index) {
				let newCustomerNameArr = this.entity.CustomerName.split(',')
				let newCustomIdArr = this.entity.CustomId.split(',')
				newCustomerNameArr.splice(index, 1)
				newCustomIdArr.splice(index, 1)
				// 暂时两种对象处理都留着 避免后续出现问题
				this.$set(this.entity, 'CustomerName', newCustomerNameArr.join(','))
				this.$set(this.entity, 'CustomId', newCustomIdArr.join(','))
				this.$set(this.newEntity, 'CustomerName', newCustomerNameArr.join(','))
				this.$set(this.newEntity, 'CustomName', this.newEntity.CustomerName)
				this.$set(this.newEntity, 'CustomId', newCustomIdArr.join(','))
				this.newEntity.CustomerNameOptions.splice(index, 1)
				this.$forceUpdate()
				console.log('删除了', index, this.options, this.newEntity, this.entity)
			},
			// 业务性质选择改变
			pickerChange(event, key) {
				let arr = event.detail.value
				// 走业务性质逻辑
				// 过滤业务性质名称
				let ExpenseTypeName = event.detail.value.map(item => {
					return item.text
				}).join('/')
				// 过滤id
				let ExpenseType = event.detail.value.map(item => {
					return item.value
				}).join('/')
				// 处理以下参数传递名字和id
				this.$set(this.newEntity, 'newExpenseTypeId', ExpenseType)
				this.$set(this.newEntity, 'ExpenseTypeId', ExpenseType)
				this.$set(this.newEntity, 'newExpenseType', ExpenseTypeName)
				this.$set(this.newEntity, 'ExpenseType', ExpenseTypeName)
				this.$set(this.newEntity, 'ExpenseTypeName', arr)

				console.log('走业务性质选择', event, key, this.newEntity)


			},
			// 业务性质 发票分类  费用类型下拉改变事件
			selectOptionsChange(event, key) {

				let optionsArr = []

				if (key === 'ExpenseType') {
					optionsArr = this.ExpenseTypeOptions
				} else if (key === 'BillType') {
					// 票据分类
					optionsArr = this.BillTypeOptions
				} else {
					// 发票分类
					optionsArr = this.InvoiceClassificationOptions
				}
				// 业务性质
				let ExpenseTypeName = optionsArr.filter(item => item.value === event)[0].text
				this.$set(this.newEntity, key + 'Name', ExpenseTypeName)
			},
			// 是否无票支出改变
			switchChange(event) {
				let IsBill = event.detail.value
				console.log('无票自处', IsBill)
				this.IsBill = IsBill

			},
			// 票面金额  报销金额实时输入事件
			inputChange(event, key) {
				const inputRule = /[^1-9]/g //只能输入正整数
				if (event < 0) {
					this.$nextTick(() => {
						this.$set(this.newEntity, key, inputRule);
					});
				}
				if (key === 'FaceAmount') {
					// 票面金额实时输入的时候 同时更新报销金额联动
					this.newEntity.ReimburseAmount = event
				}
			},
			//本条客户的数据
			Client(arr) {
				let CustomerNameArr = arr.map(item => {
					return item.cCusName
				})
				let CustomIdArr = arr.map(item => {
					return item.Id
				})
				let CustomerName = CustomerNameArr.join(',')
				let CustomId = CustomIdArr.join(',')

				this.$set(this.newEntity, "CustomerName", CustomerName);
				this.newEntity.CustomId = CustomId
				// 直接插入选中的下拉客户数组   数据额结构留着备用 需要用到直接使用即可
				this.$set(this.newEntity, "CustomerNameOptions", arr);

				console.log('子表明细------选择客户确定好后传递父组件的值', CustomerNameArr, CustomIdArr, CustomerName, CustomId, this
					.newEntity)
			},
			//选择客户
			CustomerChoice() {

				console.log('开始校验了', this.options, this.options.CustomerName)

				if (this.options.CustomerName) {
					this.$refs.MyuserAssociation.openForm();
					// 把关联的客户插入到Myuser组件标签列表里
					this.$refs.MyuserAssociation.setCustomerList(this.options.CustomerNameOptions);
					return
				}
				// 判断添加行程的主表里是否有传递过来选择的客户列表 如果没有  禁用选择客户  重新去选择行程主表客户
				this.$utils.showConfirm({
					content: '无关联客户, 是否去关联?',
					confirmText: "去关联",
				}).then(res => {
					if (res.confirm) {
						let pages = getCurrentPages() // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
						let prevPage = pages[pages.length - 2] //上一页页面实例
						uni.navigateBack({
							delta: 1,
							success: () => {
								prevPage.$vm.CustomerChoice('关联') // 返回上一页直接调用客户选择弹窗选择关联的客户
							}
						})
						console.log('点击确认了')

					} else {}
				})

				return

			},
			// 选择地址
			changeAddress(event) {
				console.log('选择地址', event)
			},
			// 出发日期和到达日期选择
			DateChange(event, key) {
				console.log('点击日期', event, key)
				this.DateType = key
				this.isCalendar = true
			},
			// 选择日期确定
			calendarChange(event) {
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************
				this.$set(this.newEntity, this.DateType, event.result);
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************
				//当前选择日期
				let ApplicationDate = new Date(this.$moment().format("YYYY-MM-DD"));
				console.log('确认日期了', this.newEntity, event, ApplicationDate, this.DateType)
				// 判断开始日期是否大于当天日期
				if (this.newEntity.DepartureDate && this.newEntity.ArrivalDate) {
					// 出发日期
					let DepartureDate = new Date(this.newEntity.DepartureDate);
					// 到达日期
					let ArrivalDate = new Date(this.newEntity.ArrivalDate);
					if (DepartureDate > ArrivalDate) {
						this.$errorToast('出发日期不能大于到达日期')
						if (this.DateType === 'DepartureDate') {
							delete this.newEntity.DepartureDate
						} else {
							delete this.newEntity.ArrivalDate
						}
						return
					}
				}
			},
			// 添加明细保存
			handleSubmitDetailSave() {
				var that = this
				console.log('差旅报销添加明细可以保存了', )
				// 是否无票状态赋值
				// this.$set(this.newEntity, 'IsBill', this.IsBill)
				this.$refs.form.validate().then(res => {
					let pages = getCurrentPages() // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
					let prevPage = pages[pages.length - 2] //上一页页面实例
					let newEntityData = JSON.parse(JSON.stringify(this.newEntity))
					this.$set(newEntityData, 'IsBill',
						this.IsBill == 1 ? true : false)
					// 单独处理票据张数  如果没有填写  默认0
					this.$set(newEntityData, 'BillsNum',
						newEntityData.BillsNum ? newEntityData.BillsNum : 0)
					console.log('差旅报销添加明细可以保存了---------------------------------------', newEntityData)


					uni.navigateBack({
						delta: 1,
						success: () => {
							prevPage.$vm.setDetailData('add', this
								.newEntity) // 给上一页绑定方法otherFun,传参地址id
						}
					})

				}).catch(err => {
					uni.hideLoading()
					that.loading = false
				})
			},
			init() {
				this.show = true

			},
			openForm(data) {
				this.init()
			},
			close() {
				this.$emit('close')
			}
		}
	}
</script>

<style lang="less" scoped>
	/* 设置 label 的样式 */
	::v-deep.uni-forms-item {
		padding-right: 40rpx !important;

		/* 例如，设置 label 的宽度和对齐方式 */
		.uni-forms-item__label {
			display: flex !important;
			justify-content: flex-end !important;
		}
	}

	// 覆盖uniapp 的 uni-data-select 央视
	::v-deep.uni-select {
		border: none !important;
	}

	// 覆盖uni-data-pirker 样式
	::v-deep.input-value-border {
		border: none !important;
	}

	// 覆盖uviewform表单form-item的下边距
	::v-deep.uni-forms-item {
		margin-bottom: 0 !important;
		border-bottom: 1px solid #EEE;
		padding-top: 20rpx !important;
		padding-bottom: 20rpx !important;
	}

	.submitButton {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 100rpx;
		/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
		height: calc(130rpx + constant(safe-area-inset-bottom));
		/* 直接扩展高度，因为padding-bottom是内边距 */
		height: calc(130rpx + env(safe-area-inset-bottom));
		/* 直接扩展高度 */
		background: #fff;
		padding-top: 10rpx;
		box-sizing: border-box;
		padding-bottom: constant(safe-area-inset-bottom);
		/*兼容 iOS<11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容iOS>= 11.2*/
		border-top: 1px solid #e9e9e9;
		padding-left: 15px;
		padding-right: 15px;
	}
</style>